import re
import traceback

from django.http import HttpResponse
from django.utils.deprecation import MiddlewareMixin
#开始发送邮件
from django.conf import settings
from django.core import mail

class MyMW(MiddlewareMixin):
    #执行路由之前被调用,在每个请求上调用，返回None或者HttpResponse对象
    def process_request(self , request):
        print("MyMW process_request do ---")

    #调用视图之前被调用，在每个请求上调用，返回None或者HttpResponse对象
    def process_view(self, request, view_func, view_args, view_kwargs):
        print("MyMW process_views do ---")

    def process_response(self , request , response):
        print("MyMW process_response do ---")
        return response

#从今以后  我只会按照下面的做
#

#访问次数限制类
class VisitLimit(MiddlewareMixin):
    visit_times = {}
    def process_request(self , request):
        #可以得到远程客户端的IP地址
        ip_address = request.META['REMOTE_ADDR']
        #可以得到客户端访问的请求路由信息
        path_url = request.path_info
        if not re.match('^/user' , path_url):
            return
        times = self.visit_times.get(ip_address , 0)
        print('ip' , ip_address , '已经访问' , times)
        self.visit_times[ip_address] = times + 1
        if times < 5:
            return
        return HttpResponse("您已经访问过" + str(times) + '次，访问被禁止')


#异常中间件捕获
class ExceptionMW(MiddlewareMixin):
    def process_exception(self , request , exception):
        print(exception)
        print(traceback.format_exc())
        #必须写好
        mail.send_mail(
            subject="编程学习的建议",  # 题目
            message=traceback.format_exc(),  # 消息内容
            from_email='1312797840@qq.com',  # 发送者
            recipient_list=settings.EX_EMAIL  # 接收者邮件列表
        )
        return HttpResponse('对不起,当前的网页有点忙')